package com.lbw.controller;


import com.lbw.order.entity.Order;
import com.lbw.product.entity.Product;
import com.lbw.properties.OrderProperties;
import com.lbw.service.IOrderService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.util.List;

@RestController
@RequestMapping("/order")
@Slf4j
//@RefreshScope // 实现配置中心动态读取最新内容
public class OrderController {

    @Resource
    private IOrderService orderService;

    @Resource
    private DiscoveryClient discoveryClient;

    @Resource
    private RestTemplate restTemplate;

    // 负载均衡api
    @Resource
    private LoadBalancerClient loadBalancerClient;

    @Resource
    private OrderProperties orderProperties;

    @GetMapping(value = "/getConfig")
    public String getConfig(){
        return "timeout: " + orderProperties.getTimeOut() + " autoConfirm: " + orderProperties.getAutoConfirm()
                 + " dbUrl: " + orderProperties.getDbUrl();
    }

    /**
     * 创建订单
     * @param productId
     * @param userId
     * @return
     */
    @PostMapping("/create")
    public Order createOrder(Long productId,Long userId) {
        Order order = orderService.createOrder(productId,userId);
        return order;
    }

    /**
     * 使用restTemplate远程调用获取商品信息
     * @param productId
     * @return
     */
    @GetMapping("getProduct/{productId}")
    public Product getProductFromRemote(@PathVariable Long productId){
        // 定义请求地址
        String url = "http://service-product/product/" + productId;
        log.info("请求地址：{}", url);

        // 发送请求，这里会自动负载均衡是因为获取restTemplate的配置类(OrderServiceConfig)添加了@LoadBalanced注解
        Product object = restTemplate.getForObject(url, Product.class);
        return object;
    }

}
